from werkzeug.wrappers import Request, Response
from module.page import Page
from routing import *
import os,paths



class App(object):
    
    SECRET_KEY = os.urandom(20)
    
    def __init__(self):
        self.url_map = {
              '/advancedsearch': lambda req: advanced_search_form(req,"advancedsearch"),
              '/customer': lambda req: customer_login_page(req,"customer"),
              '/orders': lambda req: show_order_view_table(req,"orders"),
              '/products': lambda req: show_product_view_table(req,"products"),
              None: lambda req: home(req,"Home")         
        }
    
    def dispatch_request(self,req):
        if req.path.startswith("/static"):
            return self.static(req)
        elif req.path.startswith("/static/img"):
            return self.static_img(req)
        page = Page()
        for key in self.url_map:
            if key and req.path.startswith(key):
                return Response(self.url_map[key](req),content_type='text/html')
        return Response(page.render(),content_type='text/html')
    
    def static_img(self,req):
        base = paths.ROOT_DIR
        asset_fname = os.path.join(base,req.path[1:])
        asset = file(asset_fname).read()
        return Response(asset)
    
    def static(self,req):
        base = paths.ROOT_DIR
        asset_fname = os.path.join(base,req.path[1:])
        asset = file(asset_fname).read()
        return Response(asset,content_type='text/css')
    
    def wsgi_app(self,env,res):
        req = Request(env)
        response = self.dispatch_request(req)
        return response(env,res)


    def __call__(self,env,res):
        return self.wsgi_app(env, res)